package com.hb.study.jdk.queue;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * 阻塞队列
 * 当一个线程从一个空的阻塞队列中取数据，此线程会被阻塞，直到阻塞队列不为空；
 * 当一个线程往一个满的阻塞队列中存数据，此线程会被阻塞，直到阻塞队列有空余；
 *
 * @author Mr.Huang
 * @version v0.1, BlockQueueTest.java, 2020/5/21 14:20, create by huangbiao.
 */
public class BlockQueueTest {

    static LinkedBlockingQueue queue = new LinkedBlockingQueue(10);

    public static void main(String[] args) {

        new Thread(() -> {
            System.out.println("从queue中取元素");
            Object poll = null;
            try {
                poll = queue.poll(5, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("取得结果：" + poll);
        }).start();

        new Thread(() -> {
            System.out.println("往queue中添加元素");
            boolean offer = false;
            try {
                Thread.sleep(3000);
                offer = queue.offer("111", 1, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("添加完毕：" + offer);
        }).start();
    }

}

    